<template>
  <div>
    <!-- 导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片搜索区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input
            placeholder="请输入要搜索的姓名或电话"
            v-model="keyValue"
            clearable
            @clear="getUserListByName"
            @keyup.enter.native="getUserListByName"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserListByName"
            ></el-button></el-input
        ></el-col>
        <el-col :span="2">
          <el-button
            type="primary"
            @click="addUserDialog = true"
            style="margin-top: 0"
            >添加用户</el-button
          ></el-col
        >
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="address" label="地址"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <!-- <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-share"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <!-- <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination> -->
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="用户信息"
      :visible.sync="addUserDialog"
      @close="addDialogClosed"
      width="50%"
    >
      <el-form
        :model="addForm"
        :rules="addUserRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="addForm.address"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialog = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog title="提示" :visible.sync="editDialogVisible" width="50%">
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="editForm.phone" disabled></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogClosed">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="角色信息"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClosed"
    >
      <div>
        <p>当前的用户 : {{ userInfo.username }}</p>
        <p>当前的角色 : {{ userInfo.role_name }}</p>
        <p>
          分配的新角色 :
          <el-select v-model="selectedRole" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.role_name"
              :value="item.role_name"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkphone = (rule, value, cb) => {
      const regphone =
        /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regphone.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };
    return {
      userlist: [],
      addUserDialog: false,
      addForm: {
        usename: "",
        password: "",
        address: "",
        phone: "",
      },
      addUserRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6 到 15个字符", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入手机", trigger: "blur" },
          { validator: checkphone, trigger: "blur" },
        ],
      },
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        address: [{ required: true, message: "请输入地址", trigger: "blur" }],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
      },
      // 显示角色分配对话框
      setRoleDialogVisible: false,
      //需要被分配的角色用户信息
      userInfo: {},
      //所有角色的数据列表
      rolesList: [],
      selectedRole: "",
      keyValue: "",
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      let res = await this.$http.get("/users");
      if (res.data.status !== 200) {
        return this.$message.error("获取用户列表失败");
      }
      this.userlist = res.data.data;
      console.log(this.userlist);
    },
    async getUserListByName() {
      let keyValue = this.keyValue;
      let res = await this.$http.post("users/search", {
        keyValue,
      });
      if (res.data.status !== 200) {
        return this.$message.error(res.data.message);
      }
      this.userlist = res.data.userList;
      console.log(this.userlist);
      this.$message.success(res.data.message);
    },
    // handleSizeChange(newSize) {
    //   this.queryInfo.pagesize = newSize;
    //   this.getUserList();
    // },
    // handleCurrentChange(newPage) {
    //   this.queryInfo.pagenum = newPage;
    //   this.getUserList();
    // },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        let res = await this.$http.post("users/register", this.addForm);
        if (res.data.status !== 200) {
          return this.$message.error(res.data.message);
        }
        this.getUserList();
        this.$message.success(res.data.message);
        this.addUserDialog = false;
      });
    },
    async showEditDialog(id) {
      let res = await this.$http.get("users/" + id);
      if (res.data.status !== 200) {
        return this.$message.error(res.data.message);
      }
      this.editForm = res.data.data[0];
      this.editDialogVisible = true;
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
      this.editDialogVisible = false;
    },
    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        let res = await this.$http.put("users/" + this.editForm.id, {
          address: this.editForm.address,
          username: this.editForm.username,
        });
        if (res.data.status !== 200) {
          return this.$message.error(res.data.message);
        }
        this.editDialogVisible = false;
        this.getUserList();
        this.$message.success(res.data.message);
      });
    },
    async removeUserById(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久注销该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => error);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      let res = await this.$http.delete("users/" + id);
      this.getUserList();
      return this.$message.success(res.data.message);
    },
    //展示分配角色对话框
    async setRole(userInfo) {
      this.userInfo = userInfo;
      let res = await this.$http.get("roles");
      console.log(res);
      if (res.data.status !== 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.rolesList = res.data.roleList;
      this.setRoleDialogVisible = true;
    },
    //点击按钮分配角色
    async saveRoleInfo() {
      if (!this.selectedRole) {
        return this.$message.error("请选择要分配的角色！");
      }
      let res = await this.$http.put(`/users/role/${this.userInfo.id}`, {
        role_name: this.selectedRole,
      });
      if (res.data.status !== 200) {
        return this.$message.error("分配角色失败！");
      }
      this.getUserList();
      this.setRoleDialogVisible = false;
      return this.$message.success("分配角色成功！");
    },
    setRoleDialogClosed() {
      this.selectedRole = "";
      this.userinfo = {};
    },
  },
};
</script>

<style lang="less" scope>
</style>
